/**
 * @author: phutp@younetco.com
 * @version: 0.1
 */
var Common = {};

/*{ Begin Form---------------------------------------*/
;
(function(){
    /*
     * Preload image
     * input: array source of image
     * output: all image was loaded 
     */
    $.fn.preload = function() {
        this.each(function(){
            $('<img />').attr('src', this);
        });
    };
    
    $.fn.slideImageEntry = function(options) {
        var defaults = {
            image: {width: 60, height: 60},
            wrapper: {current: 7, total: 12, displayed: 7},
            page: {current: 1, total: 1},
            offset: {min: 0, max: 0, current: 0},
            prev_page: "#",
            next_page: "#"
        };
        options = $.extend(defaults, options);
        var obj = $(this);
        var wrapper = obj.find("ul.wrapper");
        var current_photo = obj.find("li.Current");
        
        var obj_previous = obj.find("#previous");
        var obj_next = obj.find("#next");
        var obj_prev_photo = obj.find(".pre_photo");
        var obj_next_photo = obj.find(".next_photo");
        
        function init(){
            options.wrapper.current = parseInt(current_photo.attr("data-entry"), 10);
            options.wrapper.total = wrapper.find("li").length;
            options.wrapper.displayed = options.wrapper.total < options.wrapper.displayed ? options.wrapper.total : options.wrapper.displayed;
            options.offset.max = options.wrapper.total > options.wrapper.displayed ? options.wrapper.total - options.wrapper.displayed : 0;
            options.offset.current = Math.floor(options.wrapper.current / options.wrapper.displayed) * options.wrapper.displayed;
            options.offset.current = options.offset.current > options.offset.max ? options.offset.max : options.offset.current;
            options.offset.current = options.offset.current < 0 ? 0 : options.offset.current;
            
            var left = -(options.offset.current * options.image.width);
            wrapper.css("position", "relative");
            wrapper.css("left", left);
            wrapper.css("width", options.wrapper.total * options.image.width);
            
            updateStatusIcon();
            
            obj_previous.click(function(){
                prevPage();
                updateStatusIcon();
            });
            obj_next.click(function(){
                nextPage();
                updateStatusIcon();
            });
            obj_prev_photo.click(function(){
                prevPhoto();
                updateStatusIcon();
            });
            obj_next_photo.click(function(){
                nextPhoto();
                updateStatusIcon();
            });
        }
        function updateStatusIcon()
        {
            if(options.page.current == 1){
                if(options.offset.current == options.offset.min){
                    obj_previous.addClass("disabled");
                } else {
                    obj_previous.removeClass("disabled");
                }
                if(options.wrapper.current == 0){
                    obj_prev_photo.addClass("disabled");
                } else {
                    obj_prev_photo.removeClass("disabled");
                }
            }
            if(options.page.current == options.page.total){
                if(options.offset.current == options.offset.max){
                    obj_next.addClass("disabled");
                } else {
                    obj_next.removeClass("disabled");
                }
                if(options.wrapper.current == (options.wrapper.total - 1)){
                    obj_next_photo.addClass("disabled");
                } else {
                    obj_next_photo.removeClass("disabled");
                }
            }
        }
        function transmit(from, to)
        {
            var width_offset = 10;
            var time_offset = 20;
            if(from > to){
                setTimeout(function(){
                    from = (from > to + width_offset) ? from - width_offset : to;
                    wrapper.css("left", from);
                    transmit(from, to);
                }, time_offset)
            } else if(from < to) {
                setTimeout(function(){
                    from = (from < to - width_offset) ? from + width_offset : to;
                    wrapper.css("left", from);
                    transmit(from, to);
                }, time_offset)
            }
        }
        function nextPage(){
            if(options.offset.current < options.offset.max){
                from    = -(options.offset.current * options.image.width);
                offset_to = options.offset.current <= (options.offset.max - options.wrapper.displayed) ? 
                            options.offset.current + options.wrapper.displayed : 
                            options.offset.max;
                to      = -offset_to * options.image.width;
                options.offset.current = offset_to;
                transmit(from, to);
            } else {
                if(options.page.current < options.page.total){
                    location.href = options.next_page;
                }
            }
        }
        function prevPage(){
            if(options.offset.current > options.offset.min){
                from    = -(options.offset.current * options.image.width);
                offset_to = options.offset.current >= (options.offset.min + options.wrapper.displayed) ? 
                            options.offset.current - options.wrapper.displayed : 
                            options.offset.min;
                to      = -offset_to * options.image.width;
                options.offset.current = offset_to;
                transmit(from, to);
            } else {
                if(options.page.current > 1){
                    location.href = options.prev_page;
                }
            }
        }
        function nextPhoto(){
            var next_photo = current_photo.next();
            var next_url = next_photo.find(".thumbnail").attr("href");
            if(next_url == undefined){
                nextPage();
            } else {
                location.href = next_url;
            }
        }
        function prevPhoto(){
            var prev_photo = current_photo.prev();
            var prev_url = prev_photo.find(".thumbnail").attr("href");
            if(prev_url == undefined){
                prevPage();
            } else {
                location.href = prev_url;
            }
        }
        return init();
    };
    
    jQuery.fn.ymProductShareUrl = function(options) {
		if (!this.length) {
			log('Could not found the matched element!');
			return this;
		}
		var settings = {
				
		};
		function init(options)
		{	
			var $div = $(this);
			var $url_pannel = $div.find('.url_pannel');
			var $input = $div.find('input');
            $url_pannel.find('input').val(options['short-url']);
            $('.permanent_control .short_url').addClass('active');
            
            $('a.fb_button_share_custom').tipsy({gravity: options['gravity']});
			$('a.fb_button_recommend').tipsy({gravity: options['gravity']});
			
			$input.click(function(){
				$(this).select();
			})
			$('.url_pannel').click(function(e){
				return false;
			});
			$('.permanent_control .short_url').click(function(e){
                e.preventDefault();
                $('.permanent_control .long_url').removeClass('active');
                $(this).addClass('active');
                $input.val(options['short-url']).focus().select();
                
            });
            $('.permanent_control .long_url').click(function(e){
                e.preventDefault();
                $('.permanent_control .short_url').removeClass('active');
                $(this).addClass('active');
                $input.val(options['long-url']).focus().select();
                
            });
		}
		options = $.extend( settings, options );
		return this.each(function() {
            var short_url = $(this).find(".short_url").attr("href");
            var long_url = $(this).find(".long_url").attr("href");
			init.call(this,{
                'short-url' : short_url,
                'long-url'  : long_url
            });
		});

	}
     jQuery.fn.ymStatistic = function(options) {
		if (!this.length) {
			log('Could not found the matched element!');
			return this;
		}
		var settings = {
			trafficOption : {
				chart: {
					renderTo: 'traffic_container',
					type: 'line',
					spacingTop: 30,
					marginRight: 20
				},
				credits: {
					enabled : false
				},
				title: {
					text: 'Campaign Traffic'
				},
				xAxis: {
					type: 'datetime'
				},
				yAxis: {
					title: {
						text: 'Total count'
					},
					plotLines: [{
						value: 0,
						width: 1,
						color: '#808080'
					}]
				},
				tooltip: {
					formatter: function() {
							return '<b>'+ getRealSeriesName(this.series.name) +'</b><br/>'+
							unixTimeToString(this.x) +': '+ this.y;
					}
				},
				plotOptions: {
					series: {
						pointStart: '',
						pointInterval: 24 * 3600 * 1000 // one day
					}
				},
				legend: {
					layout: 'horizontal',
					verticalAlign: 'top',
					y :-30
				},
				series: ''
			},
			activityOption : {
				chart: {
					renderTo: 'container',
					type: 'line',
					marginRight: 20,
					marginBottom: 45
				},
				credits: {
					enabled : false
				},
				title: {
					text: 'Campaign activity',
					x: -20 //center
				},
				xAxis: {
					type: 'datetime'
				},
				yAxis: {
					title: {
						text: 'Total count'
					},
					plotLines: [{
						value: 0,
						width: 1,
						color: '#808080'
					}]
				},
				plotOptions: {
					series: {
						pointStart: '',
						pointInterval: 24 * 3600 * 1000 // one day
					}
				},
				tooltip: {
					formatter: function() {
							return '<b>'+ getRealSeriesName(this.series.name) +'</b><br/>'+
							unixTimeToString(this.x) +': '+ this.y;
					}
				},
				series: ''
			},
			genderOption : {
				chart: {
					renderTo: 'gender_age_container',
					type: 'column'
				},
				credits: {
					enabled : false
				},
				title: {
					text: 'Demographic chart'
				},
				xAxis: {
					categories: ''
				},
				yAxis: {
					min: 0,
					title: {
						text: 'Total count'
					}
				},
				tooltip: {
					formatter: function() {
						if (this.series.name !== 'Age')
							return '' +	this.series.name +': '+ this.y +' ('+ Math.round(this.percentage) +'%)';
						else
							return '' + this.series.name + " " + this.x + ': ' + this.y;
					}
				},
				plotOptions: {
					column: {
						stacking: 'normal',
						dataLabels: {
							enabled: true,
							color: (Highcharts.theme && Highcharts.theme.dataLabelsColor) || 'white',
							formatter: function() {
								if (this.y === 0) {
									return null;
								} else {
									return this.y;
								}
							}
						}
					}
				},
				series: ''
			}
		};
		function getRealSeriesName(string)
		{
			var startIndex = string.indexOf('Total ') + "Total ".length;
			var endIndex = string.indexOf(':');
			return string.substring(startIndex, endIndex);
		}
		function unixTimeToString(time)
		{
			var currentTime = new Date(time);
			var month = currentTime.getMonth() + 1;
			var day = currentTime.getDate();
			var year = currentTime.getFullYear();
			return month + "/" + day + "/" + year;
		}
		function init(options)
		{	
			var dlistData = [{
				'name' : $('input[name="dlist"]:checked').val(),
				'data' : options['dataAgeGender']
			}];
			var temp =options['dataPerformance'];
			var tListData = [];
			for (var i = 0 ; i < temp.length ; i++)
			{
				if (temp[i]['younet_id_key'] === 'view')
					tListData.push('view');
				else if (temp[i]['younet_id_key'] === 'like')
					tListData.push('like'); 	
				else
					tListData.push('vote');
			}
	
			var chart;
			var genderAgeChart;
			var trafficChart;
			
			//options.trafficOption.xAxis.categories = options['range'];
			options.trafficOption.plotOptions.series.pointStart = options.startDate*1000;
			options.trafficOption.series = options['dataTraffic'];
			trafficChart = new Highcharts.Chart(options.trafficOption);
		
			//options.activityOption.xAxis.categories = options['range'];
			options.activityOption.plotOptions.series.pointStart = options.startDate*1000;
			options.activityOption.series = options['dataPerformance'];
			chart = new Highcharts.Chart(options.activityOption);

			options.genderOption.xAxis.categories = options['rangeAgeGender'];
			options.genderOption.series = options['dataAgeGender'];
			genderAgeChart = new Highcharts.Chart(options.genderOption);
			
			var $div = $(this);
			$div.find('input.calendar').datepicker({
				minDate : options['minDate'],
				maxDate : options['today'],
				onSelect: function(date) {
					if ($(this).attr("name") === 'fromDate')
						$('input[name="toDate"]').datepicker("option", "minDate", date);
				},
				showOn: "both",
				buttonText		: "",
				buttonImageOnly: true,
				buttonImage: "media/style/image/icon_calendar.png"
			});
			$('form#demographicform input[name="dlist"]').change(function(){
				$('form#demographicform input[name="dlist"]').each(function(){
					$(this).attr('disabled', 'disabled');
				});
				var name = $('form#demographicform input[name="dlist"]:checked').val();
				$('form#controlform input[name="dlist"]').val(name);
				for (var i = 0; i < dlistData.length; i++)
				{
					if (dlistData[i]['name'] === name)
					{
						options.genderOption.series = dlistData[i]['data'];
						genderAgeChart = new Highcharts.Chart(options.genderOption);
						$('form#demographicform input[name="dlist"]').each(function(){
							$(this).attr('disabled', false);
						});
						return;
					}
				}	
				var link = '/dlist/' + name + '?fromDate=' + $('input[name="fromDate"]').val() + '&toDate=' + $('input[name="toDate"]').val();
				$.get(options['chartDataUrl'] + link, function(data) {
					data = JSON.parse(data);
					options.genderOption.series = data['data'];
					genderAgeChart = new Highcharts.Chart(options.genderOption);

					dlistData.push({
						'name' : name,
						'data' : data['data']
					});

					$('form#demographicform input[name="dlist"]').each(function(){
						$(this).attr('disabled', false);
					});
				});
			});
			$('.activity.control input').change(function(){
				var $checkbox = $(this);
				$('.activity.control input').each(function(){
					$(this).attr('disabled', 'disabled');
				});
				var name = $checkbox.val();
				var tlist = []
				$('.activity.control input:checked').each(function(){
					tlist.push($(this).val());
				});
				$('form#controlform input[name="tlist"]').val(tlist.join(","));
				if ($checkbox.is(':checked'))
				{
					for (var i = 0; i < tListData.length; i++)
					{
						if (tListData[i] === name)
						{
							chart.series[i].show();
							$('.activity.control input').each(function(){
								$(this).attr('disabled', false);
							});
							return;
						}
					}
					var link = '/tlist/' + name + '?fromDate=' + $('input[name="fromDate"]').val() + '&toDate=' + $('input[name="toDate"]').val();
						$.get(options['chartDataUrl'] + link, function(data) {
							data = JSON.parse(data);
							options.activityOption.series.push(data[0]);
							chart.addSeries(data[0]);

							tListData.push(name);

							$('.activity.control input').each(function(){
								$(this).attr('disabled', false);
							});
						});
				}
				else
				{
					for (var i = 0; i < tListData.length; i++)
					{
						if (tListData[i] === name)
						{
							chart.series[i].hide();
							$('.activity.control input').each(function(){
								$(this).attr('disabled', false);
							});
							return;
						}
					}
				}
			});
		}
		options = $.extend( settings, options );
		return this.each(function() {
            if ( options ) {
				init.call(this,options);
			}
		});

	}
	
	jQuery.fn.ymFormHandle = function(options) {
		if (!this.length) {
			log('Could not found the matched element!');
			return this;
		}
		var settings = {
			usingSimplePrize : false,
			maxNumberPhase : 3
		};
		options = $.extend( settings, options );
		return this.each(function() {
			if ( options ) {
				init.call(this,options);
			}
		});

	}
	function init(options)
	{
		var form = this;
        
        $("li span.tooltip_label").each(function(){
            if($(this).width() < 200){
                $(this).removeAttr("class");
                $(this).removeAttr("title");
                $(this).removeAttr("original-title");
            }
        });
        
        $('.tooltip_label', this).tipsy({html:true,gravity: $.fn.tipsy.autoNS});
        
		$(this).find(':input').change(function(){
			window.isChanged = true;
		});
		//Witch beetwen fullname and others
		$(this).find("#fullname").change(function(){
			if( this.checked == true )
			{
				$(form).find(".others_name").prop('checked',false);
				$(form).find(".others_name").eq(1).parent().next().find(':input:not(:hidden)').prop('disabled',true);
			}
			else
			{
				$(form).find(".others_name").prop('checked',true);
				$(form).find(".others_name").eq(1).parent().next().find(':input:not(:hidden)').prop('disabled',false);
			}
		});
		if( $(this).find("#fullname").is(':checked') )
		{
			$(this).find(".others_name").eq(1).parent().next().find(':input:not(:hidden)').prop('disabled',true);
		}

		$(".btn_delete").click(function(e){
			$img = $(this).parent().find('img');
			if( !$img.data('originalImg') )
			{
				$img.data('originalImg',$img.attr('src'))
			}
			if( $(this).text() === 'delete' )
			{
				$(this).parent().find(':hidden').val(1);
				$img.attr('src','media/skin/classic/image/image_not_available.gif');
				$(this).text('undelete');
			}
			else
			{
				$(this).parent().find(':hidden').val(0);
				$img.attr('src',$img.data('originalImg'));
				$(this).text('delete');
			}
		});

		$(this).find('input[name*="s_use_phase"]').each(function(i){
            if( !this.readOnly )
			{
				$(this).change(function(e){
					var isChecked;
					if( this.checked )
					{
						if( i-1 >= 0)
						{
							isChecked = $('input[name*="s_use_phase"]').get(i-1).checked;
							if( !isChecked )
							{
								alert('Please fill the previous phase first!');
								this.checked = false;
							}
						}
					}
					else
					{
						if( i+1 < ($('input[name*="s_use_phase"]').length) )
						{
							isChecked = $('input[name*="s_use_phase"]').get(i+1).checked;
							if( isChecked )
							{
								alert('The next phase is available, so you can not uncheck here!');
								this.checked = true;
							}
						}
					}
					$form = $(this).parent().parent().next();
					if( !this.checked )
					{
						$form.hide();
					}
					else
					{
						$form.show();
					}
					return true;
				});
			}
            $form = $(this).parent().parent().next();
            if( !this.checked )
            {
                $form.hide();
            }
            else
            {
                $form.show();
            }
            return true;
		});

		$(this).find(":checkbox").each(function(i){
			if( $(this).prop('readonly') )
			{
				$(this).click(function(e){
					e.preventDefault();
					e.stopImmediatePropagation();
					return false;
				});
				$(this).keydown(function(e){
					e.preventDefault();
					e.stopImmediatePropagation();
					return false;
				});
			}
		});

		$(this).find('.calendar').each(function(){
			if( !this.disabled )
			{
				$(this).datepicker({
					dateFormat: 'M d, yy',
					showOn: "both",
					buttonImageOnly: true,
					buttonText		: "",
					buttonImage: "media/style/image/icon_calendar.png"
				});
			}
		});
		$(window).bind('beforeunload',function(event) {
			window.isSubmitting = window.isSubmitting || false;
			window.isChanged	= window.isChanged || false;
			try{
				$(form).find('textarea').each(function(){
					if( $(this).tinymce().isDirty() )
					{
						window.isChanged = true;
					}
				});
			}
			catch(e){

			}

			if( !window.isSubmitting  && window.isChanged)
			{
				var message = 'WARNING: You are currently editing the contest.  Those edits will be lost if you click OK.';
				event.returnValue = message;
				return message;
			}
			window.isSubmitting = false;
		});
		$(this).submit(function() {
			$(window).unbind("beforeunload");
		});
	}

	function hide(element)
	{
		var $ddTag = $(element).parent();
		$ddTag.prev().hide();
		$ddTag.hide();
	}
	function show(element)
	{
		var $ddTag = $(element).parent();
		$ddTag.prev().show();
		$ddTag.show();
	}
	function log(obj) {
		if( window.console && console.log ) console.log(obj) ;
	}
})(jQuery);
/*------------------------------------------}End Form*/
function selectTab(id)
{
	$('#' + id).addClass('active');
}

function addTab(caption, url)
{
	if (caption.length > 30)
	{
		caption = caption.substr(0, 30) + "...";
	}
	$('#tabs').find("li").removeClass('active');
	$('#tabs').append('<li class="active"><a href="'+url+'">'+caption+'</a></li>');
}
function validateEmail(email) {
    var re = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
    return re.test(email);
}

function setrawcookie (name, value, expires, path, domain, secure) {
    if (typeof expires === 'string' && (/^\d+$/).test(expires)) {
        expires = parseInt(expires, 10);
    }

    if (expires instanceof Date) {
        expires = expires.toGMTString();
    } else if (typeof(expires) === 'number') {
        expires = (new Date(expires * 1e3)).toGMTString();
    }

    var r = [name + '=' + value],
        s = {},
        i = '';
    s = {
        expires: expires,
        path: path,
        domain: domain
    };
    for (i in s) {
        if (s.hasOwnProperty(i)) { // Exclude items on Object.prototype
            s[i] && r.push(i + '=' + s[i]);
        }
    }

    return secure && r.push('secure'), this.window.document.cookie = r.join(";"), true;
}
function setcookie (name, value, expires, path, domain, secure) {
    return setrawcookie(name, encodeURIComponent(value), expires, path, domain, secure);
}
function getcookie(c_name)
{
	var i,x,y,ARRcookies=document.cookie.split(";");
	for (i=0;i<ARRcookies.length;i++)
	{
		x=ARRcookies[i].substr(0,ARRcookies[i].indexOf("="));
		y=ARRcookies[i].substr(ARRcookies[i].indexOf("=")+1);
		x=x.replace(/^\s+|\s+$/g,"");
		if (x==c_name)
		{
			return unescape(y);
		}
	}
	return false;
}
function base64_decode (data) {
    var b64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
    var o1, o2, o3, h1, h2, h3, h4, bits, i = 0,
        ac = 0,
        dec = "",
        tmp_arr = [];

    if (!data) {
        return data;
    }

    data += '';

    do { // unpack four hexets into three octets using index points in b64
        h1 = b64.indexOf(data.charAt(i++));
        h2 = b64.indexOf(data.charAt(i++));
        h3 = b64.indexOf(data.charAt(i++));
        h4 = b64.indexOf(data.charAt(i++));

        bits = h1 << 18 | h2 << 12 | h3 << 6 | h4;

        o1 = bits >> 16 & 0xff;
        o2 = bits >> 8 & 0xff;
        o3 = bits & 0xff;

        if (h3 == 64) {
            tmp_arr[ac++] = String.fromCharCode(o1);
        } else if (h4 == 64) {
            tmp_arr[ac++] = String.fromCharCode(o1, o2);
        } else {
            tmp_arr[ac++] = String.fromCharCode(o1, o2, o3);
        }
    } while (i < data.length);

    dec = tmp_arr.join('');

    return dec;
}

function utf8_decode (str_data) {
    // http://kevin.vanzonneveld.net
    var tmp_arr = [],
        i = 0,
        ac = 0,
        c1 = 0,
        c2 = 0,
        c3 = 0;

    str_data += '';

    while (i < str_data.length) {
        c1 = str_data.charCodeAt(i);
        if (c1 < 128) {
            tmp_arr[ac++] = String.fromCharCode(c1);
            i++;
        } else if (c1 > 191 && c1 < 224) {
            c2 = str_data.charCodeAt(i + 1);
            tmp_arr[ac++] = String.fromCharCode(((c1 & 31) << 6) | (c2 & 63));
            i += 2;
        } else {
            c2 = str_data.charCodeAt(i + 1);
            c3 = str_data.charCodeAt(i + 2);
            tmp_arr[ac++] = String.fromCharCode(((c1 & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
            i += 3;
        }
    }

    return tmp_arr.join('');
}